package com.mediacloud.app.newsmodule.activity.audio

import android.annotation.SuppressLint
import android.content.ComponentName
import android.content.Intent
import android.graphics.Rect
import android.media.MediaMetadata
import android.media.session.PlaybackState
import android.os.Build
import android.os.Bundle
import android.os.IBinder
import android.util.Log
import android.view.Gravity
import android.view.View
import android.view.WindowManager
import androidx.annotation.RequiresApi
import androidx.appcompat.app.AppCompatActivity
import androidx.core.content.ContextCompat
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import androidx.recyclerview.widget.SimpleItemAnimator
import com.chinamcloud.audioserver.APSHelper
import com.chinamcloud.audioserver.APSLifecycleKit
import com.chinamcloud.audioserver.MusicEntity
import com.eventTrack.CDPTrackReportManager
import com.eventTrack.TXReportManager
import com.gyf.barlibrary.ImmersionBar
import com.jaeger.library.StatusBarUtil
import com.luck.picture.lib.tools.DoubleUtils
import com.lzf.easyfloat.EasyFloat
import com.lzf.easyfloat.interfaces.OnPermissionResult
import com.lzf.easyfloat.permission.PermissionUtils
import com.mediacloud.app.assembly.util.Utility
import com.mediacloud.app.model.fragment.BaseFragment
import com.mediacloud.app.model.news.ArticleItem
import com.mediacloud.app.model.news.CatalogItem
import com.mediacloud.app.newsmodule.R
import com.mediacloud.app.newsmodule.activity.audio.BaseAudioActivityHalfCCTV7.AUDIO_TYPE
import com.mediacloud.app.newsmodule.fragment.baoliao.api.SpiderCmsApi
import com.mediacloud.app.newsmodule.utils.*
import com.mediacloud.app.quanzi.model.BaseDataBean
import com.scwang.smartrefresh.layout.api.RefreshLayout
import com.scwang.smartrefresh.layout.listener.OnRefreshListener
import com.tencent.liteav.demo.superplayer.model.entity.AlbumDetail
import com.tencent.liteav.demo.superplayer.model.entity.PublishArticlePage
import com.tencent.liteav.demo.superplayer.model.entity.VideoAlbumNew
import com.utils.read.AudioFloatManager
import kotlinx.android.synthetic.main.audio_album_program_layout.*
import retrofit2.Call
import retrofit2.Callback
import retrofit2.Response
import tv.danmaku.ijk.media.player.IMediaPlayer

class AudioAlbumListFragment : BaseFragment(), IScrollView, OnRefreshListener, Runnable {
    var adapter: AudioAlbumProgramAdapter = AudioAlbumProgramAdapter()
    var apsKit: APSLifecycleKit? = null
    var selectProgramAdapter: SelectProgramAdapter? = null
    var selectProgramWin: AudioAlbumProgramWinX2? = null
    var orderDir = "desc"//desc-倒序。asc-正序默认倒序
    var data: ArrayList<AlbumDetail>? = ArrayList()

    var activity: AudioAlbumDetailActivity? = null
    var floatTop = 0
    var currentArticleItem:ArticleItem?=null
    var currentPos = 0

    var smoothScroller: TopSmoothScroller? = null
    private val maskView: View? = null
    override fun getLayoutResID(): Int {
        return R.layout.audio_album_program_layout
    }

    private var albumId: String? = null
    private var collectionName: String? = null
    private var contentColumn: String? = null
    private var isFollowed: Boolean? = false
    override fun initView() {
        albumId = arguments?.getString("AlbumId")
        collectionName = arguments?.getString("collectionName")
        contentColumn = arguments?.getString("contentColumn")
        isFollowed = arguments?.getBoolean("isFollowed",false)
        getDataList(albumId)
        refreshLayout.setEnableLoadMore(false)
        refreshLayout.setEnableRefresh(true)
        refreshLayout.setOnRefreshListener(this)
        recyclerView.layoutManager = LinearLayoutManager(requireContext())
        recyclerView.adapter = adapter
        recyclerView.addOnScrollListener(object : RecyclerView.OnScrollListener() {
            override fun onScrollStateChanged(recyclerView: RecyclerView, newState: Int) {
                super.onScrollStateChanged(recyclerView, newState)
                when (newState) {
                    RecyclerView.SCROLL_STATE_IDLE -> {
                        commonExpose()
                    }
                }
            }
        })
        (recyclerView.getItemAnimator() as SimpleItemAnimator).setSupportsChangeAnimations(false)
        //   data = arguments?.getParcelableArrayList("PROGRAM_LIST")
        //    adapter.setNewData(data)
        activity = requireActivity() as AudioAlbumDetailActivity
        iniAPSKit()
        adapter.apsKit = apsKit
        adapter.setOnItemClickListener { adapter, _, position ->
            if (DoubleUtils.isFastDoubleClick()) {
                return@setOnItemClickListener
            }
            val albumDetail = adapter.getItem(position) as AlbumDetail
            if (apsKit?.getCurrentTaskId() != "${activity?.articleItem?.id}") {
                play(position)
                //首次播放刷新指定的位置即可
                adapter.notifyItemChanged(position)
            } else {
                try {//保存旧id
                    val oldId = apsKit?.getCurrentMusic()?.id
                    apsKit?.switchTo(position, false)
                    //切换之后获取新id
                    val newId = apsKit?.getCurrentMusic()?.id
                    //如果两个id不一致就刷新
                    if (oldId != newId) {
                        adapter.notifyDataSetChanged()
                    }
                } catch (e: Exception) {
                }
            }

            val intent = Intent(requireContext(), AudioVodDetailActivityHalfCCTV7::class.java)
            val b = Bundle()


            activity?.data?.let {
                if (it.colorPickType == "2") {
                    it.backgroundColor?.let {
                        try {
                            b.putInt("bgColor", it.toInt());
                        } catch (e: Exception) {
                            e.printStackTrace()
                        }
                    }
                }
            }


            b.putParcelable("cdata", activity?.catalogItem)
            b.putString("albumId", "${albumDetail.albumId}")
            b.putString("orderDir", orderDir)
            //  b.putParcelableArrayList("RECOMMEND_LIST",activity?.data?.seriesDto?.seriesRecommendDtos)
            b.putInt(AUDIO_TYPE, 2)
            // b.putParcelableArrayList("PROGRAM_LIST", data as ArrayList)

            FacadeInvoker.getFacadeData(requireContext(), activity?.articleItem?.id.toString())
            val bean = adapter.getItem(position) as AlbumDetail
            currentPos = position
            currentArticleItem = ArticleItem()
            currentArticleItem?.let{
                it.id = bean.articleId.toLong()
                it.title = bean.title
                it.publishDate = bean.publishDate
                it.shortTitle = bean.title
                it.type = bean.type.toInt()
                it.hitCount = bean.getHit_Count()
                it.publishdate_format = bean.publishDate
                it.logoImgSize = activity?.articleItem?.logoImgSize
                it.logo = bean.logo
                it.prop4 = bean.duration
                it.authorId = bean.authorId
                it.Author = bean.author
                if (TXReportManager.getInstance().firstTabInfo.tabName == "视听") {
                    CDPTrackReportManager.getInstance()
                        .ShortVideoClick( it,position)
                }
                NewsItemClickUtils.addHistory(requireContext(), it, CatalogItem())
                b.putParcelable("data", it)
                b.putString("articleId", "${it.id}")
                b.putString("AudioAlbumArticleId", "${activity?.articleItem?.id}")
                intent.putExtras(b)
                startActivityForResult(intent,10)
                TXReportManager.getInstance()
                    .app_jhapp_radio_cllct_ctntlst_interact(it,contentColumn,collectionName,position,isFollowed)

            }

        }
        smoothScroller = TopSmoothScroller(requireContext())
        BindEventBus(this, adapter)

        order.setOnClickListener {
            if (order.text.contains("正序")){
                order.text = "倒序"
                order.setCompoundDrawablesWithIntrinsicBounds(null,null,
                    ContextCompat.getDrawable(it.context,R.drawable.icon_album_desc),null)
                orderDir = "desc"
            }else{
                order.text = "正序"
                order.setCompoundDrawablesWithIntrinsicBounds(null,null,
                    ContextCompat.getDrawable(it.context,R.drawable.icon_album_asc),null)
                orderDir = "asc"
            }
            getDataList(albumId)
        }
    }

    var needSendTx = false
    override fun setUserVisibleHint(isVisibleToUser: Boolean) {
        super.setUserVisibleHint(isVisibleToUser)
        if (isVisibleToUser && needSendTx) {
            commonExpose()
            needSendTx = false
        }
    }

    var mTotalRecords: Int? = null
    var firstPageSize = 1000
    private fun getDataList(albumId: String?) {
        mTotalRecords = null
        SpiderCmsApi.getSpiderCmsApi(requireContext())
            .findPublishArticlePage(albumId, 1, firstPageSize,orderDir,"publishDate")
            .enqueue(object : Callback<PublishArticlePage> {
                override fun onResponse(
                    call: Call<PublishArticlePage>, response: Response<PublishArticlePage>?
                ) {
                    if (getActivity() == null || requireActivity().isFinishing || requireActivity().isDestroyed) {
                        return
                    }
                    refreshLayout.finishRefresh()
                    if (response?.isSuccessful == true && response.body()?.success == true) {
                        mTotalRecords = response.body()?.data?.totalRecords
                        response.body()?.data?.pageRecords?.let {
                           data?.let{data->
                               data.clear()
                               data.addAll(it)
                           }
                            videoSum.text = "共${response.body()?.data?.totalRecords}集"
                            adapter.setNewData(it)
                            if (userVisibleHint) {
                                commonExpose()
                            } else {
                                needSendTx = true
                            }
                        }
                    }

                }

                override fun onFailure(call: Call<PublishArticlePage>, t: Throwable) {
                    getAllData()
                }
            })


    }

    private fun getAllData() {
        SpiderCmsApi.getSpiderCmsApi(requireContext()).findAllPublishArticles(albumId)
            .enqueue(object : Callback<BaseDataBean<List<AlbumDetail>>> {
                override fun onResponse(
                    call: Call<BaseDataBean<List<AlbumDetail>>>,
                    response: Response<BaseDataBean<List<AlbumDetail>>>
                ) {
                    if (getActivity() == null || requireActivity().isFinishing || requireActivity().isDestroyed) {
                        return
                    }
                    refreshLayout?.finishRefresh()
                    if (response.isSuccessful) {
                        val body = response.body()
                        if (body != null && body.isSuccess) {
                            body.data?.let {
                                if (data == null || data?.size == 0) {
                                    data?.clear()
                                    data?.addAll(it)
                                    adapter.setNewData(it)
                                    if (userVisibleHint) {
                                        commonExpose()
                                    } else {
                                        needSendTx = true
                                    }
                                } else {
                                    if (mTotalRecords != 0 && mTotalRecords == it.size && firstPageSize < it.size) {
                                        adapter.data.addAll(it.subList(firstPageSize, it.size))
                                        data= ArrayList(adapter.data)
                                        videoSum.text = "共${data?.size}集"
                                        adapter.notifyItemRangeInserted(
                                            firstPageSize,
                                            it.size - firstPageSize)
                                    } else {
                                        data?.clear()
                                        data?.addAll(it)
                                        adapter.setNewData(it)
                                        if (userVisibleHint) {
                                            commonExpose()
                                        } else {
                                            needSendTx = true
                                        }
                                    }
                                }

                            }
                        }
                    }
                }

                override fun onFailure(call: Call<BaseDataBean<List<AlbumDetail>>>, t: Throwable) {

                }

            })
    }

    fun backgroundAlpha(bgAlpha: Float) {
        val lp: WindowManager.LayoutParams = requireActivity().window.attributes
        lp.alpha = bgAlpha
        requireActivity().window.addFlags(WindowManager.LayoutParams.FLAG_DIM_BEHIND)
        requireActivity().window.setAttributes(lp)
    }

    var callBack: APSLifecycleKit.APSCallback? = null
    var startPlayTime : Long = 0
    private fun iniAPSKit() {
        callBack = object : APSLifecycleKit.APSCallback() {
            override fun onBufferingUpdate(mediaPlayer: IMediaPlayer?, percent: Int) {
            }

            override fun onCompletion(mediaPlayer: IMediaPlayer?) {
                adapter.notifyDataSetChanged()
            }

            override fun onMetadataChanged(metadata: MediaMetadata?) {
                super.onMetadataChanged(metadata)
            }

            @RequiresApi(Build.VERSION_CODES.LOLLIPOP)
            override fun onPlaybackStateChanged(state: PlaybackState?) {
                super.onPlaybackStateChanged(state)
                adapter.notifyDataSetChanged()

                when(state?.state){

                    PlaybackState.STATE_PAUSED->{
                        apsKit?.let{
                            CDPTrackReportManager.getInstance().RadioSubjectEndPlay(currentArticleItem,(it.getCurrentPosition()-startPlayTime)/1000)
                        }
                    }
                    PlaybackState.STATE_PLAYING->{
                        apsKit?.let{
                            startPlayTime = it.getCurrentPosition()
                            AudioFloatManager.getInstance(requireContext()).startPlayTime=startPlayTime
                        }
                        currentArticleItem?.let{
                            CDPTrackReportManager.getInstance().RadioSubjectStartPlay(it,currentPos+1,adapter.data.size,(activity as AudioAlbumDetailActivity).componentTitle)
                        }
                    }

                }
            }

            override fun onPrepared(mediaPlayer: IMediaPlayer?) {
                adapter.notifyDataSetChanged()
            }

            override fun onServiceConnected(name: ComponentName?, iBinder: IBinder?) {
                super.onServiceConnected(name, iBinder)
                adapter.notifyDataSetChanged()
            }

            @SuppressLint("SetTextI18n")
            override fun onUpdateProgress(mediaPlayer: IMediaPlayer?) {
                mediaPlayer?.let {
                    if (it.duration != 0L) {
                        var percent: Int = (it.currentPosition * 100 / it.duration).toInt() + 1;
                        if (percent >= 100) {
                            percent = 99
                        }
                        adapter.playingPositionTV?.setText("已听$percent%")
                    }

                }

            }
        }
        apsKit = APSLifecycleKit(
            requireContext(), "${activity?.articleItem?.id}", null, callBack
        )
    }

    private fun play(position: Int) {
        val list: MutableList<MusicEntity> = ArrayList()
        this.data?.let { datas ->
            val size = datas.size
            for (i in 0 until size) {
                val item = datas[i]
                if (item.audioSimpleDtos.isNullOrEmpty()) {
                    val music = MusicEntity("${item.title}", "")
                    music.id = item.articleId
                    music.otherExt = "event:audio_album_program/${item.articleId}"
                    list.add(music)
                } else {
                    val move = item.audioSimpleDtos?.get(0)
                    val music = MusicEntity(
                        "${item.title}",
                        if (move.formats != null && move.formats.size > 0) "${move.formats[0].url}"
                        else ""
                    )
                    music.id = item.articleId
                    music.otherExt = "event:audio_album_program/${item.articleId}"
                    list.add(music)
                }

            }
        }
        apsKit?.autoPlay = true
        apsKit?.setData(list, position)

    }

    private fun openFloat() {
        if (PermissionUtils.checkPermission(requireContext())) {
            showFloat()
        } else {
            activity?.let {
                AudioFloatManager.showPermissionAsk(it, object : OnPermissionResult {
                    override fun permissionResult(isOpen: Boolean) {
                        if (isOpen) {
                            showFloat()
                        }
                    }
                })
            }
        }
    }

    private fun showFloat() {
        AudioFloatManager.getInstance(requireContext()).article = currentArticleItem
        AudioFloatManager.getInstance(requireContext()).canPackUp = false
        AudioFloatManager.getInstance(requireContext()).catalogItem = activity?.catalogItem
        if (floatTop == 0) {
            floatTop =
                Utility.getScreenHeight(requireContext()) - requireContext().resources.getDimensionPixelSize(
                    R.dimen.dimen71
                ) - StatusBarUtil.getStatusBarHeight(requireContext())
            if (ImmersionBar.hasNavigationBar(requireActivity())) {
                floatTop -= ImmersionBar.getNavigationBarHeight(requireActivity())
            }
        }
        try {
            AudioFloatManager.getInstance(requireContext())
                .show(floatTop, apsKit?.getCurrentMusic()?.musicTitle)
        } catch (e: Exception) {
        }

    }

    override fun getScrollView(): View {
        return recyclerView
    }

//    override fun onDestroy() {
//        super.onDestroy()
//        apsKit?.let {
//            if (!it.isTaskPlaying()) {
//                KillMusicUtils.hideReadNewsWin()
//            }
//        }
//    }


    fun toSmoothScrollTop(position: Int) {
        recyclerView.postDelayed({
            if (activity == null || requireActivity().isFinishing || requireActivity().isDestroyed) {
                return@postDelayed
            }
            smoothScroller?.let {
                it.targetPosition = position
                recyclerView.layoutManager?.startSmoothScroll(it)
            }

        }, 100)
    }

    override fun onRefresh(refreshLayout: RefreshLayout) {
        getDataList(albumId)
    }

    override fun onDestroyView() {
        super.onDestroyView()
        if (callBack is APSHelper.OnMediaStateChangeListener) {
            apsKit?.helper?.removeMediaStateChangeListener(callBack!!)
        }
    }

    override fun run() {
        recyclerView?.let {
            try {
                val manager = recyclerView.layoutManager as LinearLayoutManager
                val firstPosition = manager.findFirstVisibleItemPosition()
                val lastPosition = manager.findLastVisibleItemPosition()
                if (lastPosition < 0 || firstPosition < 0) {
                    return
                }
                for (i in firstPosition until lastPosition + 1) {
                    val bean = adapter.data[i]
                    bean?.let {
                        if (recyclerView.getGlobalVisibleRect(Rect())) {
                            val articleItem = ArticleItem()
                            articleItem.id = bean.articleId.toLong()
                            articleItem.title = bean.title
                            articleItem.publishDate = bean.publishDate
                            articleItem.shortTitle = bean.title
                            articleItem.type = bean.type.toInt()
                            articleItem.hitCount = bean.getHit_Count()
                            articleItem.prop4 = bean.duration
                            articleItem.authorId = bean.authorId
                            articleItem.authorNickName = bean.authorNickName
                            TXReportManager.getInstance().app_jhapp_radio_cllct_ctntlst_imp(articleItem,contentColumn,collectionName,i,isFollowed)
                        }
                    }
                }
            } catch (e: java.lang.Exception) {
                e.printStackTrace()
            }

        }
    }

    /**
     * 曝光通用延迟
     */
    private fun commonExpose() {
        recyclerView.removeCallbacks(this@AudioAlbumListFragment)
        recyclerView.postDelayed(this@AudioAlbumListFragment, TXReportManager.EXPOSURE_DELAY)
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (requestCode == 10 && resultCode == AppCompatActivity.RESULT_OK){
            apsKit?.let{
               // CDPTrackReportManager.getInstance().RadioSubjectEndPlay(currentArticleItem,(it.getCurrentPosition()-startPlayTime)/1000)
            }
        }
    }
}
/**
 *    private fun checkPlay(position:Int) {
val cm = SystemServiceManager.getConnectivityManager(requireContext())
val networkInfo = cm.activeNetworkInfo
networkInfo?.let {
if(networkInfo.type == ConnectivityManager.TYPE_MOBILE){
if(MMKV.defaultMMKV().getBoolean(XKey.VIDEO_TIP_KEY, true)){
val inflater =requireContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE) as LayoutInflater
val contentView = inflater.inflate(R.layout.audio_notic, null)
val title = contentView.findViewById<TextView>(R.id.audio_notice_title)
val btn1 = contentView.findViewById<TextView>(R.id.audio_notice_btn1)
val btn2 = contentView.findViewById<TextView>(R.id.audio_notice_btn2)
val dialog = Dialog(requireContext(), R.style.loadingDialogStyle)
//点击继续以后不再提示，点击关闭下次继续提示
title.setText(R.string.audio_notice_isNotWifi)
btn1.setText(R.string.audio_notice_goON)
btn2.setText(R.string.audio_notice_close)
btn1.setOnClickListener {
dialog.dismiss()
toPlay(position)
}
btn2.setOnClickListener {
dialog.dismiss()
}
dialog.show()
}else{
toPlay(position)
}
}else if (networkInfo.type == ConnectivityManager.TYPE_WIFI){
toPlay(position)
}
}
}
private fun toPlay(position: Int){
play(position)
//首次播放刷新指定的位置即可
adapter.notifyItemChanged(position)
openFloat()
}
 */